package com.zxjbyte.yiyi.framework.common.annotation.validated;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import com.zxjbyte.yiyi.framework.common.annotation.AllowedValues;
import com.zxjbyte.yiyi.framework.common.util.CollXUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Author zhangxingjia
 * @Date 2024/9/10 20:32
 * @Version: 1.0
 */
public class AllowedValuesValidator implements ConstraintValidator<AllowedValues, Object> {

    private List<Object> allowedValues;

    @Override
    public void initialize(AllowedValues constraintAnnotation) {
        if(ArrayUtil.isNotEmpty(constraintAnnotation.intValues())){
            allowedValues = CollXUtil.toList(Arrays.stream(constraintAnnotation.intValues()).boxed().toArray(Integer[]::new));
        } else {
            allowedValues = CollXUtil.toList(constraintAnnotation.values());
        }

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if(Objects.isNull(value)){
            return true;
        }
        if(!(value instanceof Integer)){
            value = Convert.toStr(value);
        }
        return CollXUtil.contains(allowedValues, value);
    }
}
